package cn.itsource.org.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import cn.itsource.base.service.impl.BaseServiceImpl;
import cn.itsource.base.util.*;
import cn.itsource.global.exception.BusinessException;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.domain.Shop;
import cn.itsource.org.domain.ShopAuditLog;
import cn.itsource.org.domain.bo.ShopBo;
import cn.itsource.org.domain.dto.EmployeeDto;
import cn.itsource.org.domain.dto.ShopDto;
import cn.itsource.org.domain.dto.ShopRejectDto;
import cn.itsource.org.mapper.EmployeeMapper;
import cn.itsource.org.mapper.ShopAuditLogMapper;
import cn.itsource.org.mapper.ShopMapper;
import cn.itsource.org.query.ShopQuery;
import cn.itsource.org.service.IShopService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 业务实现类：
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private TextCensor textCensor;
    @Autowired
    private ImgCensor imgCensor;
    @Autowired
    private EmailUtil emailUtil;
    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;

    private static final String IMG_PATH =  "http://115.159.88.63:8800";

    @Override
    public PageList<Shop> queryPage(ShopQuery query){
        if(query.getCurrentPage() < 1){
            throw new RuntimeException("");
        }
        //分页查询
        List<Shop> shopList = shopMapper.query(query);
        //创建分页接收对象
        PageList<Shop> pageList = new PageList();
        //设置分页数据
        pageList.setData(shopList);
        //设置分页总条数
        pageList.setCount(shopMapper.queryCount(query));
        return pageList;
    }

    @Override
    @Transactional
    public AjaxResult settlement(ShopDto shopDto) {
        //判断店铺名字是否正确
        if(textCensor.TextCensor(shopDto.getName())){
            throw new BusinessException(ErrorCode.BUSINESS_IS_SHOP_NAME_ERROR.getCode());
        }
        //判断店铺地址是否正确
        if(textCensor.TextCensor(shopDto.getAddress())){
            throw new BusinessException(ErrorCode.BUSINESS_IS_SHOP_ADDRESS_ERROR.getCode());
        }
        //判断图片是否正确
//        if(imgCensor.ImgCensor(IMG_PATH+shopDto.getLogo())){
//            throw new BusinessException(ErrorCode.BUSINESS_IS_SHOP_ADDRESS_ERROR.getCode());
//        }


        //确认密码是否正确
        EmployeeDto admin = shopDto.getAdmin();
        if(!admin.getPassword().equals(admin.getComfirmPassword())){
            throw new BusinessException(ErrorCode.BUSINESS_REGISTER_ERROR.getCode());
        }
        //为了保证数据不能出现同一个账号
        Employee employeeName = employeeMapper.selectByName(admin.getUsername());
        if(employeeName != null){
            throw new BusinessException(ErrorCode.BUSINESS_REGISTER_USERNAME_ERROR.getCode());
        }
        Shop shopName = shopMapper.findByNameAndAddress(shopDto);
        if(shopName != null){
            throw new BusinessException(ErrorCode.BUSINESS_REGISTER_SHOP_NAME_ERROR.getCode());
        }
        //保存 employee信息
        Employee employee = new Employee();
        BeanUtils.copyProperties(admin,employee);//执行了赋值
        String salt = RandomUtil.randomString(32); //生成32位的盐值
        String md5Pwd = SecureUtil.md5(admin.getPassword() + salt); //加密加盐
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);
        employee.setState(0);
        employeeMapper.save(employee);

        //保存shop的信息
        Shop shop = new Shop();
        BeanUtils.copyProperties(shopDto,shop);
        shop.setRegisterTime(new Date());
        shop.setState(1);
        shop.setAdminId(employee.getId());
        super.save(shop);
        employee.setShopId(shop.getId());
        employeeMapper.update(employee);

//        employee.setShop_id(?);
        //保存 loginInof信息
        //保存 shop 信息
        return AjaxResult.me();
    }

    /**
     * 功能实现在业务层做
     * @param shopRejectDto
     * @return
     */
    @Override
    @Transactional
    public AjaxResult reject(ShopRejectDto shopRejectDto) {
        //修改店铺状态
        Long shopId = shopRejectDto.getShopId();
        Shop shop = super.selectById(shopId);
        shop.setState(4);
        super.update(shop);
        //使用邮箱通知？ 通过 shopId 找 员工id 在找 邮箱
        Long adminId = shop.getAdminId();//employee的id
        Employee employee = employeeMapper.selectById(adminId);
        String email = employee.getEmail();
        emailUtil.sendMessage("店铺审核通知",shopRejectDto.getNote(),email);

        //日志记录
        ShopAuditLog shopAuditLog = new ShopAuditLog();
        shopAuditLog.setShopId(shop.getId());
        shopAuditLog.setState(4);
        //shopAuditLog.setAuditId()//审核人暂时不管
        shopAuditLog.setNote(shopRejectDto.getNote());
        shopAuditLogMapper.save(shopAuditLog);

        return AjaxResult.me();
    }

    @Override
    public AjaxResult countRegisterTimeEcharts() {
        List<ShopBo> shopBos = shopMapper.countRegisterTimeEcharts();
        Map<String,List<String>> result = new HashMap<>();
//        List<String> key = shopBos.stream().map(ShopBo::getKey).collect(Collectors.toList());
//        List<String> value = shopBos.stream().map(ShopBo::getValue).collect(Collectors.toList());
        List<String> key = new ArrayList<>();
        List<String> value = new ArrayList<>();
        for (ShopBo shopBo : shopBos) {
            key.add(shopBo.getKey());
            value.add(shopBo.getValue());
        }
        result.put("x",key);
        result.put("y",value);
        return AjaxResult.me().setResultObj(result);
    }

    @Override
    public AjaxResult pass(ShopRejectDto shopRejectDto) {
        //写逻辑  已经明确了 这里只能是通过的
        Long shopId = shopRejectDto.getShopId();
        Shop shop = shopMapper.selectById(shopId);
        shop.setState(2);//修改状态
        shopMapper.update(shop);
        //发送一个邮件
        Long adminId = shop.getAdminId();
        Employee employee = employeeMapper.selectById(adminId);
        String path = "<a href='http://127.0.0.1:8080/shop/activation?shopId="+shopId+"'>点击激活</a>";
        emailUtil.sendMessage("店铺审核通知",path,employee.getEmail());
        //日志记录
        return AjaxResult.me();
    }

    @Override
    public AjaxResult activation(Long shopId) {
        //修改店铺为以激活
        //员工要修改1
        //添加一个loginInfo数据
        return AjaxResult.me();
    }
}
